package com.hjqjl.whdemo.dialog.dialogfragment;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import com.hjqjl.whdemo.R;

//设置属性和点击事件可参考自定义布局CustomDialogFragment
public class DialogLoadingFragment extends DialogFragment {
    private Context pActivity;

    public static DialogLoadingFragment newInstance(String content) {
        DialogLoadingFragment fragment = new DialogLoadingFragment();
        Bundle bundle = new Bundle();
        bundle.putString("content", content);
        fragment.setArguments(bundle);
//        fragment.setCancelable(false);// 不可以用“返回键”取消
        return fragment;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        pActivity = context;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        String content = "";
        if (bundle != null) {
            content = bundle.getString("content");
        }

        AlertDialog loadingDialog = new AlertDialog.Builder(pActivity).create();
        loadingDialog.show();
        loadingDialog.setCanceledOnTouchOutside(false);//点击周边是否取消

        Window window = loadingDialog.getWindow();
        if (window != null) {
            window.setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            window.setBackgroundDrawableResource(android.R.color.transparent);//去掉白色背景
            window.setContentView(R.layout.dialog_loading);
            ImageView ivLoading = window.findViewById(R.id.iv_dialog_loading);
            // 加载动画
            Animation loadingAnimation = AnimationUtils.loadAnimation(pActivity, R.anim.loading_roate);
            // 使用ImageView显示动画
            ivLoading.startAnimation(loadingAnimation);
            TextView tvContent = (window.findViewById(R.id.tv_dialog_loading));
            tvContent.setText(content);
        }
        return loadingDialog;
    }
}
